package com.watchme.license.create;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;
import java.util.prefs.Preferences;

import javax.security.auth.x500.X500Principal;

import com.watchme.license.util.JLDateUtil;
import com.watchme.license.util.LicenseCheckModel;

import de.schlichtherle.license.CipherParam;
import de.schlichtherle.license.DefaultCipherParam;
import de.schlichtherle.license.DefaultKeyStoreParam;
import de.schlichtherle.license.DefaultLicenseParam;
import de.schlichtherle.license.KeyStoreParam;
import de.schlichtherle.license.LicenseContent;
import de.schlichtherle.license.LicenseManager;
import de.schlichtherle.license.LicenseParam;

/**
 * CreateLicense
 *
 * @author melina
 */
public class CreateLicense {

	private static String propertiesPath = "createparam.properties";
	// Lisence类型：1、正式证书、0：临时证书（临时证书只校验时间，而且只有30天）
	private String licenseType;

	// common param
	private static String PRIVATEALIAS = "";
	private static String KEYPWD = "";
	private static String STOREPWD = "";
	private static String SUBJECT = "";
	// private static String licPath = "";
	private String priPath = "";
	// license content
	private String issuedTime = "";
	private String notBefore = "";
	private String notAfter = "";
	private String ipAddress = "";
	private String macAddress = "";
	private String consumerType = "";
	private int consumerAmount = 0;
	private String info = "";
	private String licenseId;

	private final static X500Principal DEFAULTHOLDERANDISSUER = new X500Principal("CN=Duke、OU=JavaSoft、O=Sun Microsystems、C=US");

	private String licPath;

	public void setParam(String licPathParam, String ipAddressParam, String notBeforeParam, String notAfterParam, String licenseIdParam) {
		setParam(licPathParam, ipAddressParam, null, notBeforeParam, notAfterParam, licenseIdParam);
	}

	public void setParam(String licPathParam, String ipAddressParam, String macAddressParam, String notBeforeParam, String notAfterParam, String licenseIdParam) {
		Properties prop = new Properties();
		// InputStream in = getClass().getResourceAsStream(propertiesPath);
		InputStream in = null;
		try {
			// InputStream in = new FileInputStream(propertiesPath);
			in = CreateLicense.class.getClassLoader().getResourceAsStream(propertiesPath);
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		PRIVATEALIAS = prop.getProperty("PRIVATEALIAS");
		KEYPWD = prop.getProperty("KEYPWD");
		STOREPWD = prop.getProperty("STOREPWD");
		SUBJECT = prop.getProperty("SUBJECT");
		KEYPWD = prop.getProperty("KEYPWD");
		priPath = prop.getProperty("priPath");
		licPath = licPathParam;
		macAddress = macAddressParam;
		ipAddress = ipAddressParam == null || "".equals(ipAddressParam.trim()) ? prop.getProperty("ipAddress") : ipAddressParam;
		String licName = prop.getProperty("licName");

		if (!licPath.endsWith(File.separator)) {
			licPath += File.separator;
		}

		String ipDir = this.licPath + ipAddress;
		// 递归创建文件夹
		mkDir(new File(ipDir));
		this.licPath = ipDir + File.separator + licName;
		// 删除之前创建的
		File file = new File(licPath);
		if (file.exists() && file.isFile()) {
			System.out.println(file.delete());
		}
		// license content
		licenseType = "1";// 正式证书
		issuedTime = prop.getProperty("issuedTime");
		notBefore = notBeforeParam == null || "".equals(notBeforeParam.trim()) ? prop.getProperty("notBefore") : notBeforeParam;
		notAfter = notAfterParam == null || "".equals(notAfterParam.trim()) ? prop.getProperty("notAfter") : notAfterParam;
		licenseId = licenseIdParam;
		consumerType = prop.getProperty("consumerType");
		consumerAmount = Integer.valueOf(prop.getProperty("consumerAmount"));
		info = prop.getProperty("info");

	}

	public void setTempParam(String licPathParam) {
		Properties prop = new Properties();
		// InputStream in = getClass().getResourceAsStream(propertiesPath);
		InputStream in = null;
		try {
			// InputStream in = new FileInputStream(propertiesPath);
			in = CreateLicense.class.getClassLoader().getResourceAsStream(propertiesPath);
			prop.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		PRIVATEALIAS = prop.getProperty("PRIVATEALIAS");
		KEYPWD = prop.getProperty("KEYPWD");
		STOREPWD = prop.getProperty("STOREPWD");
		SUBJECT = prop.getProperty("SUBJECT");
		KEYPWD = prop.getProperty("KEYPWD");
		priPath = prop.getProperty("priPath");
		licPath = licPathParam;
		String licName = prop.getProperty("licName");

		if (!licPath.endsWith(File.separator)) {
			licPath += File.separator;
		}

		String ipDir = this.licPath + "temp";
		// 递归创建文件夹
		mkDir(new File(ipDir));
		this.licPath = ipDir + File.separator + licName;
		// 删除之前创建的
		File file = new File(licPath);
		if (file.exists() && file.isFile()) {
			System.out.println(file.delete());
		}
		// license content
		licenseType = "0";// 临时证书
		issuedTime = prop.getProperty("issuedTime");
		notBefore = JLDateUtil.getNowDate();
		notAfter = JLDateUtil.addDay(30);
		consumerType = prop.getProperty("consumerType");
		consumerAmount = Integer.valueOf(prop.getProperty("consumerAmount"));
		info = prop.getProperty("info");

	}

	public void mkDir(File file) {
		if (!file.exists()) {
			if (file.getParentFile().exists()) {
				file.mkdir();
			} else {
				mkDir(file.getParentFile());
				// 已经存在不创建
				file.mkdirs();
			}
		}
	}

	public String create() {
		String result = "";
		try {
			File file = new File(licPath);
			LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(initLicenseParams0());
			licenseManager.store((createLicenseContent()), file);
			result = file.getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("create license file failure");

		}
		System.out.println("create license file successfully");
		return result;
	}

	private LicenseParam initLicenseParams0() {
		Preferences preference = Preferences.userNodeForPackage(CreateLicense.class);

		CipherParam cipherParam = new DefaultCipherParam(STOREPWD);

		KeyStoreParam privateStoreParam = new DefaultKeyStoreParam(CreateLicense.class, priPath, PRIVATEALIAS, STOREPWD, KEYPWD);
		LicenseParam licenseParams = new DefaultLicenseParam(SUBJECT, preference, privateStoreParam, cipherParam);
		return licenseParams;
	}

	public final LicenseContent createLicenseContent() {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

		LicenseCheckModel licenseCheckModel = new LicenseCheckModel();
		licenseCheckModel.setIpAddress(ipAddress);
		licenseCheckModel.setLicenseId(licenseId);
		licenseCheckModel.setLicenseType(licenseType);
		// licenseCheckModel.setIpMacAddress(macAddress);

		LicenseContent content = null;
		content = new LicenseContent();
		content.setSubject(SUBJECT);
		content.setHolder(DEFAULTHOLDERANDISSUER);
		content.setIssuer(DEFAULTHOLDERANDISSUER);
		try {
			content.setIssued(format.parse(issuedTime));
			content.setNotBefore(format.parse(notBefore));
			content.setNotAfter(format.parse(notAfter));
			content.setExtra(licenseCheckModel);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		content.setConsumerType(consumerType);
		content.setConsumerAmount(consumerAmount);
		content.setInfo(info);

		return content;
	}

	public String getLicPath() {
		return licPath;
	}

	public void setLicPath(String licPath) {
		this.licPath = licPath;
	}

}